package com.serviceprovider.business.module.admin.user.validator;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.admin.role.model.Role;
import com.serviceprovider.business.module.admin.role.services.dao.interfaces.IRoleService;

import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

//~--- JDK imports ------------------------------------------------------------

import java.util.List;

/**
 * Created in IntelliJ IDEA. User: tryk Date: 14.05.11 Time: 0:42
 */
@Repository("roleValidator")
public class RoleValidator implements Validator {
    @Autowired
    private IRoleService roleService;

    @Override
    public boolean supports(Class aClass) {
        return Role.class.equals(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        Role newRole = (Role) o;

        if (StringUtils.isEmpty(newRole.getName())) {
            errors.rejectValue("name", "role.create.notNull");
        }

        List<Role> roles = roleService.findAll();

        for (Role role : roles) {
            if (role.getName().equals(newRole.getName())) {
                errors.rejectValue("name", "role.create.alreadyExists");
            }
        }
    }
}



